﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace WindowsTest
{
    public class TestBll
    {

        #region inner

        /// <summary>
        /// 执行HTTP GET请求。
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="data">请求提交的参数</param>
        /// <returns>HTTP响应</returns>
        public static string DoGet(string url, int timeout = 5000, IWebProxy proxy = null, bool useNagleAlgorithm = false)
        {
            HttpWebRequest req = GetWebRequest(url, "GET", timeout, proxy, useNagleAlgorithm);
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";

            using (HttpWebResponse rsp = (HttpWebResponse)req.GetResponse())
            {
                Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
                return GetResponseAsString(rsp, encoding);
            }
        }

        /// <summary>
        /// 组装普通文本请求参数。
        /// </summary>
        /// <param name="request">Key-Value形式请求参数字典</param>
        /// <returns>URL编码后的请求数据</returns>
        private static string BuildQuery(JObject data)
        {
            StringBuilder postData = new StringBuilder();
            bool hasParam = false;
            foreach (var keyPair in data.Properties())
            {
                // 忽略参数名或参数值为空的参数
                if (!String.IsNullOrEmpty(keyPair.Name))
                {
                    if (hasParam)
                    {
                        postData.Append("&");
                    }
                    postData.Append(keyPair.Name);
                    postData.Append("=");
                    postData.Append(keyPair.Value.ToString());
                    hasParam = true;
                }
            }
            return postData.ToString();
        }

        /// <summary>
        /// 执行HTTP POST请求。
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="jsonPostData">请求参数</param>
        /// <returns>HTTP响应</returns>
        public static string DoPost(string url, string jsonPostData, int timeout = 5000, IWebProxy proxy = null, bool useNagleAlgorithm = false)
        {
            HttpWebRequest req = GetWebRequest(url, "POST", timeout, proxy, useNagleAlgorithm);
            req.ContentType = "application/json;charset=utf-8";
            Byte[] postData = Encoding.UTF8.GetBytes(jsonPostData);
            Stream reqStream = req.GetRequestStream();
            reqStream.Write(postData, 0, postData.Length);
            reqStream.Close();

            using (HttpWebResponse rsp = (HttpWebResponse)req.GetResponse())
            {
                Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
                return GetResponseAsString(rsp, encoding);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        /// <param name="method"></param>
        /// <param name="Timeout"></param>
        /// <returns></returns>
        private static HttpWebRequest GetWebRequest(string url, string method, int timeout, IWebProxy proxy, bool useNagleAlgorithm)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.ServicePoint.Expect100Continue = false;
            req.ServicePoint.UseNagleAlgorithm = useNagleAlgorithm;
            req.Proxy = proxy;
            req.Method = method;
            req.KeepAlive = true;
            req.UserAgent = "CommonAPI.V1.0.0.0";
            req.Accept = "application/json";
            req.Timeout = timeout;
            return req;
        }

        /// <summary>
        /// 把响应流转换为文本。
        /// </summary>
        /// <param name="rsp">响应流对象</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>响应文本</returns>
        private static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
        {
            Stream stream = null;
            StreamReader reader = null;

            try
            {
                // 以字符流的方式读取HTTP响应
                stream = rsp.GetResponseStream();
                reader = new StreamReader(stream, encoding);
                return reader.ReadToEnd();
            }
            finally
            {
                // 释放资源
                if (reader != null) reader.Close();
                if (stream != null) stream.Close();
                if (rsp != null) rsp.Close();
            }
        }

        #endregion
    }
}
